package com.mrduan.otgfilemanager.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.shike.baselibrary.utils.SharepreferenceUtils;

import java.sql.Date;
import java.util.Calendar;

/**
 * Created by snoopy on 2018/5/23.
 */

public class SuanFa {

    private String key = "yuan";
    private String time = "time";
    private Context context ;
    public SuanFa(Context context) {
        this.context = context;
    }

    public String getYuan() {
        if (getValue() == 0) {
            return "";
        }

        if (differentDaysByMillisecond() > 5) {
            saveValue("0");
            return "";
        }

        return getValue() + "元补贴";
    }

    public void saveYuan() {

        if (isToday()) {
            return;
        }

        int value = getValue();
        if (value == 0) {
            saveValue("1");
        } else if (value == 16) {
            saveValue("16");
        } else {
            saveValue(value*2 + "");
        }

    }

    public void clear() {
        saveValue("0");
    }

    public boolean isToday () {
        String lastSave = CalendarUtil.timesAsCustom(SharepreferenceUtils.getString(context,time,"0"),"yyyyMMdd");
        if (lastSave.equals(CalendarUtil.timesAsCustom("yyyyMMdd"))) { // 还是今天
            return true;
        }
        return false;
    }

    public int getValue() {
        return Integer.valueOf(SharepreferenceUtils.getString(context,key,"0"));
    }

    private void saveValue(String s) {
        SharepreferenceUtils.saveString(context,key,s);
        SharepreferenceUtils.saveString(context,time, Calendar.getInstance().getTimeInMillis()+"");
    }


    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     * @return
     */
    private int differentDaysByMillisecond() {
        long i = Long.parseLong(SharepreferenceUtils.getString(context,time,"0"));

        int days = (int) ((Calendar.getInstance().getTime().getTime() - new java.util.Date(i).getTime()) / (1000*3600*24));
        return days;
    }

}
